package com.rskj.cashbook.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RedisUtil {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public boolean exists(String key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    public void expire(String key, long timeout, TimeUnit unit) {
        redisTemplate.expire(key, timeout, unit);
    }

    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public void set(String key, Object value, long timeout, TimeUnit unit) {
        log.info("set key: {}, value: {}, timeout: {}, unit: {}", key, value, timeout, unit);
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public void hPut(String key, String hashKey, Object value) {
        redisTemplate.opsForHash().put(key, hashKey, value);
    }

    public Object hGet(String key, String hashKey) {
        return redisTemplate.opsForHash().get(key, hashKey);
    }

    public void lPush(String key, Object value) {
        redisTemplate.opsForList().leftPush(key, value);
    }

    public List<Object> lRange(String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    public void delete(String key) {
        log.info("delete key: {}", key);
        redisTemplate.delete(key);
    }

    /**
     * 根据模式删除多个key
     */
    public void deleteByPattern(String pattern) {
        try {
            Set<String> keys = getKeysByPattern(pattern);
            if (keys != null && !keys.isEmpty()) {
                redisTemplate.delete(keys);
                log.info("Deleted {} keys matching pattern: {}", keys.size(), pattern);
            }
        } catch (Exception e) {
            log.error("Error deleting keys by pattern: {}", e.getMessage(), e);
        }
    }

    /**
     * 根据模式获取key列表
     */
    public Set<String> getKeysByPattern(String pattern) {
        try {
            return redisTemplate.keys(pattern);
        } catch (Exception e) {
            log.error("Error getting keys by pattern: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 获取key的数量
     */
    public long getKeyCount(String pattern) {
        try {
            Set<String> keys = getKeysByPattern(pattern);
            return keys != null ? keys.size() : 0;
        } catch (Exception e) {
            log.error("Error getting key count: {}", e.getMessage(), e);
            return 0;
        }
    }

    public static String getTokenKey(String ip, String username) {
        return JwtUtil.TOKEN_PREFIX + username + ":" + ip;
    }
}
